﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using FuDanMicTools;

namespace SimpleTestFrameForNFC
{
    public partial class FrmMain : Form
    {
        private bool debug = false;

        /**
         * 设备
         */
        private PCI1733And1734 PCI1733And1734;
        private WT1800 WT1800;
        private ITECH8912E ITECH8912E_1;
        private ITECH8912E ITECH8912E_2;
        private ChromaACSource ChromaACSource;
        private UDP3305S UDP3305S;
        FuDanMicTools.FuDanMicTools NFC;

        /**
         * 重要参数设置
         */
        private List<TestItem> testItems = new List<TestItem>();
        private byte[] GTIN = new byte[6];
        private string sn;
        private int passFail = 0;
        private int failedECCdoe = 0;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            tbSN.Focus();

            if (!debug)
            {
                PCI1733And1734 = new PCI1733And1734();
                PCI1733And1734.connect();

                ChromaACSource = new ChromaACSource();
                ChromaACSource.Connect("30");

                WT1800 = new WT1800();
                WT1800.Connect("1");
                WT1800.InitForAM00000();

                ITECH8912E_1 = new ITECH8912E();
                ITECH8912E_1.Connect("10");
                ITECH8912E_1.SetFunction(FunctionType.VOLT);
                ITECH8912E_1.SenseOn(true);

                ITECH8912E_2 = new ITECH8912E();
                ITECH8912E_2.Connect("11");
                ITECH8912E_2.SetFunction(FunctionType.VOLT);
                ITECH8912E_2.SenseOn(true);

                UDP3305S = new UDP3305S();
                UDP3305S.connect(7);

                NFC = new FuDanMicTools.FuDanMicTools();
                GTIN[0] = 6;
                GTIN[1] = 88;
                GTIN[2] = 163;
                GTIN[3] = 135;
                GTIN[4] = 65;
                GTIN[5] = 60;
                
            }
        }

        private async void tbSN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                PCI1733And1734.RelaycontrolFull(0, "00001000"); //要改成自锁
                while (true)
                {
                    int startFlag = PCI1733And1734.GetBitStatus(0, 0);
                    if (startFlag == 1)
                    {
                        PCI1733And1734.RelaycontrolFull(0, "00111000"); //要改成两个电磁阀+自锁
                        Thread.Sleep(500);                        
                        await Task.Run(startTest);

                        tbSN.Text = "";
                        tbSN.Focus();
                        return;
                    }
                    Thread.Sleep(500);
                }
            }
        }

        private void showData(TestItem item)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => {
                    //UI
                    int index = dgvShowData.Rows.Add();
                    dgvShowData.Rows[index].Cells[0].Value = item.ECCode.ToString();
                    dgvShowData.Rows[index].Cells[1].Value = item.Desc.ToString();
                    dgvShowData.Rows[index].Cells[2].Value = item.LowerLimit.ToString();
                    dgvShowData.Rows[index].Cells[3].Value = item.Value.ToString();
                    dgvShowData.Rows[index].Cells[4].Value = item.UpperLimit.ToString();
                    dgvShowData.Rows[index].Cells[5].Value = item.Result.ToString();
                    if (item.Result == 0)
                    {
                        dgvShowData.Rows[index].DefaultCellStyle.BackColor = Color.MediumSeaGreen;
                    }
                    else
                    {
                        dgvShowData.Rows[index].DefaultCellStyle.BackColor = Color.IndianRed;
                        passFail = 1;
                        failedECCdoe = item.ECCode;
                        throw new TestException();
                    }
                }));
            }

            //保存数据
            testItems.Add(item);
        }

        private void clearDataGridView() {
            dgvShowData.Rows.Clear();
            lblStatus.BackColor = Color.FloralWhite;
            passFail = 0;
            failedECCdoe = 0;
            testItems.Clear();
        }

        private string[] CreateDataString(string SN, List<TestItem> TestResult, string Station, string OrderNum, string ICCode)
        {
            /*
            * 拼接字符串示例
            * strWrite = "" + Chr(39) + SN2 + Chr(39) + "," + Chr(39) + Chr(39) + "," + Chr(39) + "SocketIndex1" + Chr(39) + "," + Chr(39) + Format(Now, "yyyy-mm-dd hh:mm:ss") + Chr(39) + "," + Chr(39) + CStr(CostTime) + Chr(39) + _
               "," + Chr(39) + txtICcode1.Text + Chr(39) + "," + Chr(39) + "AA" + Chr(39) + "," + Chr(39) + ComboPline.Text + Chr(39) + "," + Chr(39) + txtWorkNo2.Text + Chr(39) + "," + Chr(39) + ComboStationNo.Text + Chr(39) + "," + TestResult2 + _
               "," + Chr(39) + Chr(39) + "," + Chr(39) + "prod1_QJZM-EQ1900" + Chr(39) + "," + Chr(39) + FailedEC2 + Chr(39) + "," + Chr(39) + iProductionMode + Chr(39) + "," + Chr(39) + Chr(39) + "," + Chr(39) + Chr(39) + "," + "0" + ";" + _
               "10" + "," + CStr(MDBResult(10, 2)) + ";" + "100" + "," + CStr(MDBResult(100, 2)) + ";" + "110" + "," + CStr(MDBResult(110, 2)) + ";" + "120" + "," + CStr(MDBResult(120, 2)) + ";" + "130" + "," + CStr(MDBResult(130, 2)) + ";" + "140" + "," + CStr(MDBResult(140, 2)) + ";" + "150" + "," + CStr(MDBResult(150, 2)) + ";"
            */
            StringBuilder sb = new StringBuilder("");
            sb.Append(string.Format("'{0}',", SN));
            sb.Append("'','SocketIndex1',");
            string dateStr = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
            sb.Append(string.Format("'{0}',", dateStr));
            sb.Append(string.Format("{0},", 0));      //CostTtime
            sb.Append(string.Format("'{0}',", ICCode));
            sb.Append("'AA',");
            sb.Append(string.Format("'{0}',", Station));
            sb.Append(string.Format("'{0}',", OrderNum));
            sb.Append("'FCTEST_100',");     //必填项，否则无法上传数据
            sb.Append(string.Format("{0},'',", passFail));   //0 pass
            sb.Append(string.Format("'{0}',", "NFC"));
            sb.Append(string.Format("'{0}',", failedECCdoe));
            sb.Append("'3','','',0;");  //量产模式
            foreach (var detail in TestResult)
            {
                sb.Append(string.Format("{0},{1};", detail.ECCode, detail.Value));
            }
            string dataStr = sb.ToString();

            StringBuilder fileName = new StringBuilder("");
            Random rd = new Random();
            fileName.Append(string.Format("{0}@NFC_SocketIndex1@{1}.txt", SN, (int)(rd.Next(999988889) + 11111)));
            return new string[] { fileName.ToString(), dataStr };
        }

        private void SaveDataToLocal(string SN, string ICCode, List<TestItem> TestResult)
        {
            if (passFail == 0)
            {
                lblStatus.BackColor = Color.MediumSeaGreen;
            }
            else {
                lblStatus.BackColor = Color.IndianRed;
            }

            string[] vs = CreateDataString(SN, TestResult, "FCT", "", ICCode);
            StreamWriter sw = new StreamWriter(string.Format("{0}\\{1}", "D:\\TEDATA_KKD\\FCT", vs[0]), false);
            sw.Write(vs[1]);
            sw.Close();
        }

        private void startTest()
        {
            try
            {
                clearDataGridView();
                sn = tbSN.Text.Trim();
                /**
                 * 烧录
                 */
                //showData(new TestItem(1, "NFC Reader init", 0, NFC.init(), 0));
                NFC.init();
                showData(new TestItem(2, "program", 0, NFC.download("srec/TW NFC FUDANWEI 0_10V 18W V1.1.srec"), 0));
                byte[] ReturnCIN = new byte[8];
                showData(new TestItem(3, "write CIN", 0, NFC.WriteCIN(sn, 11, 1, 59, 6, 1, ref ReturnCIN), 0));
                showData(new TestItem(4, "compare CIN", 0, NFC.compareCIN(ReturnCIN), 0));
                showData(new TestItem(5, "set current: 250mA", 0, NFC.setPWM(250, 500), 0));

                /**
                 * 测试
                 */
                Thread.Sleep(500);
                NFC.setPWM(250, 500);
                NFC.disconnect();
                ITECH8912E_1.SetValueAndOn(30);
                ITECH8912E_2.SetValueAndOn(30);
                UDP3305S.SetVolAndON(0, 0);
                ChromaACSource.SetOutputAndOn(230);
                PCI1733And1734.RelaycontrolFull(0, "10111000");
                Thread.Sleep(1500);
                double[] vs = WT1800.Read(16);
                double[] result = ITECH8912E_1.Measure();
                showData(new TestItem(2110, "CH1 Iout", 0, result[1] * 1000, 2));
                result = ITECH8912E_2.Measure();
                showData(new TestItem(2120, "CH2 Iout", 0, result[1] * 1000, 2));
                showData(new TestItem(2130, "Pin", 0.5, vs[2], 1));
                showData(new TestItem(2140, "Vin", 227, vs[0], 233));
                UDP3305S.SetVolAndON(0.9, 0);
                Thread.Sleep(2000);
                result = ITECH8912E_1.Measure();
                showData(new TestItem(2230, "CH1 Iout", 2.5, result[1] * 1000, 5));
                UDP3305S.SetVolAndON(9.5, 0);
                Thread.Sleep(2000);
                vs = WT1800.Read(16);
                result = ITECH8912E_1.Measure();
                showData(new TestItem(2280, "CH1 Pin", 8, vs[2], 10.5));
                showData(new TestItem(2290, "CH1 PF", 0.9, vs[3], 0.95));
                showData(new TestItem(2300, "CH1 Iout", 237.5, result[1] * 1000, 262.5));
                showData(new TestItem(2310, "CH1 Vout", 29.5, result[0], 30.5));
                double Eff = Math.Round(result[2] / vs[2], 4) * 100;
                showData(new TestItem(2340, "CH1 EFF", 76, Eff, 81));
                UDP3305S.SetVolAndON(0, 0.9);
                Thread.Sleep(2000);
                result = ITECH8912E_2.Measure();
                showData(new TestItem(2440, "CH2 Iout", 2.5, result[1] * 1000, 5));
                UDP3305S.SetVolAndON(0, 9.5);
                Thread.Sleep(2000);
                vs = WT1800.Read(16);
                result = ITECH8912E_2.Measure();
                showData(new TestItem(2490, "CH2 Pin", 8, vs[2], 10.5));
                showData(new TestItem(2500, "CH2 PF", 0.9, vs[3], 0.95));
                showData(new TestItem(2530, "CH2 Iout", 237.5, result[1] * 1000, 262.5));
                showData(new TestItem(2540, "CH2 Vout", 29.5, result[0], 30.5));
                Eff = Math.Round(result[2] / vs[2], 4) * 100;
                showData(new TestItem(2550, "CH2 EFF", 76, Eff, 81));
                PCI1733And1734.RelaycontrolFull(0, "00111000");
                Thread.Sleep(1000);
                NFC.init();
                NFC.setPWM(500, 500);
                NFC.disconnect();
                ITECH8912E_1.SetValueAndOn(36);
                ITECH8912E_2.SetValueAndOn(36);
                UDP3305S.SetVolAndON(0, 0);
                PCI1733And1734.RelaycontrolFull(0, "10111000");
                Thread.Sleep(2000);
                vs = WT1800.Read(16);
                result = ITECH8912E_1.Measure();
                showData(new TestItem(3110, "CH1 Iout", 0, result[1] * 1000, 2));
                ITECH8912E_2.Measure();
                showData(new TestItem(3120, "CH2 Iout", 0, result[1] * 1000, 2));
                showData(new TestItem(3130, "Pin", 0.5, vs[2], 1));
                showData(new TestItem(3140, "Vin", 227, vs[0], 233));
                UDP3305S.SetVolAndON(0.9, 0);
                Thread.Sleep(2000);
                result = ITECH8912E_1.Measure();
                showData(new TestItem(3230, "CH1 Iout", 5, result[1] * 1000, 10));
                UDP3305S.SetVolAndON(9.5, 0);
                Thread.Sleep(2000);
                vs = WT1800.Read(16);
                result = ITECH8912E_1.Measure();
                showData(new TestItem(3280, "CH1 Pin", 20, vs[2], 22.5));
                showData(new TestItem(3290, "CH1 PF", 0.97, vs[3], 1));
                showData(new TestItem(3300, "CH1 Iout", 475, result[1] * 1000, 525));
                showData(new TestItem(3310, "CH1 Vout", 35.5, result[0], 36.5));
                Eff = Math.Round(result[2] / vs[2], 4) * 100;
                showData(new TestItem(3340, "CH1 EFF", 84, Eff, 88));
                UDP3305S.SetVolAndON(0, 0.9);
                Thread.Sleep(2000);
                result = ITECH8912E_2.Measure();
                showData(new TestItem(3440, "CH2 Iout", 5, result[1] * 1000, 10));
                UDP3305S.SetVolAndON(0, 9.5);
                Thread.Sleep(2000);
                result = ITECH8912E_2.Measure();
                vs = WT1800.Read(16);
                showData(new TestItem(3490, "CH2 Pin", 20, vs[2], 22.5));
                showData(new TestItem(5500, "CH2 PF", 0.97, vs[3], 1));
                showData(new TestItem(3530, "CH2 Iout", 475, result[1] * 1000, 525));
                showData(new TestItem(3540, "CH2 Vout", 35.5, result[0], 36.5));
                Eff = Math.Round(result[2] / vs[2], 4) * 100;
                showData(new TestItem(3550, "CH2 EFF", 84, Eff, 88));
                UDP3305S.SetVolAndON(5, 5);
                Thread.Sleep(2000);
                vs = WT1800.Read(16);
                showData(new TestItem(3650, "Pin", 20, vs[2], 22.5));
                showData(new TestItem(3660, "PF", 0.97, vs[3], 1));
                result = ITECH8912E_1.Measure();
                double b = result[2];
                showData(new TestItem(3670, "CH1 Iout", 237.5, result[1] * 1000, 262.5));
                showData(new TestItem(3680, "CH1 Vout", 35.5, result[0], 36.5));
                result = ITECH8912E_2.Measure();
                showData(new TestItem(3690, "CH2 Iout", 237.5, result[1] * 1000, 262.5));
                showData(new TestItem(3700, "CH2 Vout", 35.5, result[0], 36.5));
                Eff = Math.Round((result[2] + b) / vs[2], 4) * 100;
                showData(new TestItem(3710, "EFF", 84, Eff, 88));
                Thread.Sleep(200);
                UDP3305S.SetVolAndON(0, 0);
                ChromaACSource.SetOutputAndOn(0);
                PCI1733And1734.RelaycontrolFull(0, "00000000");
                PCI1733And1734.RelaycontrolFull(1, "00000000");
                PCI1733And1734.RelaycontrolFull(2, "00000000");
                PCI1733And1734.RelaycontrolFull(3, "00000000");
            }
            catch (TestException e)
            {
                //do nothing
            }
            finally {
                /**
                 * 保存数据到本地
                 */
                SaveDataToLocal(sn, "AM509840055", testItems);
            }
        }
    }
}
